/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.task.handler.impl;

import com.hyts.infodb.config.SpringContextConfiguration;
import com.hyts.infodb.error.subclass.ProcessError;
import com.hyts.infodb.task.bean.TaskModel;
import com.hyts.infodb.task.execute.TaskExecuteService;
import com.hyts.infodb.task.handler.AsyncTaskHandler;
import com.hyts.infodb.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.task.handler.impl
 * @author:LiBo/Alex
 * @create-date:2020-03-06 17:48
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Service
public class DefaultAsyncTaskHandler<P,R> implements AsyncTaskHandler<TaskModel<P>, CompletableFuture<R>> {

    @Autowired
    SpringContextConfiguration springContextConfiguration;

    @Async
    @Override
    public CompletableFuture<R> execute(TaskModel<P> param) {
        //判断是否为空!
        if(Objects.isNull(springContextConfiguration) || StringUtils.isBlank(param.getTaskNo())){
            throw new ProcessError("执行异步调用：传入得参数或者taskNo为空!");
        }
        Object bean = springContextConfiguration.getApplicationContext().getBean(param.getTaskNo());
        // 判断是否属于系统定义级别得操作执行类
        if(Objects.isNull(bean) || ! (bean instanceof TaskExecuteService)){
            throw new ProcessError(String.format("无法获取改taskNO对应得系统执行类:%s",
                    param.getTaskNo()));
        }
        //判断是否为空!
        if(Objects.isNull(param.getTaskParam())){
            return (CompletableFuture<R>) CompletableFuture.completedFuture(((TaskExecuteService)bean).execute());
        }else{
            return (CompletableFuture<R>) CompletableFuture.completedFuture(((TaskExecuteService)bean).execute(param.getTaskParam()));
        }
    }
}
